import 'package:casdon/app/config/env/common_config.dart';
import 'package:casdon/common/state/common_net_status.dart';
import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/core/extentions/string_validation.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/network/business_exception.dart';
import 'package:casdon/modules/home/application/notification/tuya_auth_notifier.dart';
import 'package:casdon/modules/login/application/notifier/login_notifier.dart';
import 'package:casdon/modules/login/data/api/login_api.dart';
import 'package:casdon/modules/login/data/api/valide_code_type.dart';
import 'package:casdon/modules/login/domain/states/login_code_state.dart';
import 'package:casdon/modules/login/domain/states/login_wechat_state.dart';
import 'package:casdon/modules/login/domain/usecases/login_usecase.dart';
import 'package:casdon/modules/login/domain/usecases/verify_otp_usecase.dart';
import 'package:casdon/modules/login/providers/login_code_provider.dart';
import 'package:casdon/modules/login/providers/login_provider.dart';
import 'package:fluwx/fluwx.dart';
import 'package:uuid/uuid.dart';

enum WeChatLoginStep { auth, login, sendCode, verifyCode, afterbindingLogin }

class LoginWechatNotifier extends LoginNotifier<LoginWechatState> {
  WeChatLoginStep step = WeChatLoginStep.auth;

  Future<void> auth() async {
    state = state.copyWith(
      status: CommonNetStatus.idle,
      message: null,
      errorCode: null,
      socialCode: null,
      socialState: null,
      account: null,
      code: null,
    );

    if (false == state.agreed) {
      setFailure(msg: "请先同意用户协议");
      return;
    }
    step = WeChatLoginStep.auth;
    try {
      Fluwx().removeSubscriber(_responseWechat1);
      Fluwx().addSubscriber(_responseWechat1);
      final result = await Fluwx().authBy(
        which: NormalAuth(scope: CommonConfig.WX_authScope, state: Uuid().v4()),
      );
      if (result == false) {
        setFailure(msg: "微信授权失败");
        return;
      }
      setSuccess("微信授权成功");
    } catch (e) {
      Log.e("微信授权失败", e.toString(), StackTrace.current);
    }
  }

  void _responseWechat1(WeChatResponse response) {
    if (response.isSuccessful == false) {
      setFailure(msg: "微信授权失败");
      Log.e("微信授权失败", response, null);
    } else {
      switch (response) {
        case WeChatAuthResponse(:var code, :var state):
          this.state = this.state.copyWith(
            socialCode: code,
            socialState: state,
          );
        default:
          Log.i("通用响应处理");
      }
      setSuccess("微信授权成功");

      login();
    }
  }

  void updateCode(String value) {
    state = state.copyWith(
      code: value,
      version: state.version,
      status: CommonNetStatus.idle,
    );
  }

  void login() async {
    if (step == WeChatLoginStep.auth) {
      step = WeChatLoginStep.login;
    } else if (step == WeChatLoginStep.verifyCode) {
      step = WeChatLoginStep.afterbindingLogin;
    } else {
      Log.e(
        "微信登录步骤错误,当前非WeChatLoginStep.verifyCode,WeChatLoginStep.auth",
        Object(),
        StackTrace.current,
      );
      return;
    }
    state = state.copyWith(
      status: CommonNetStatus.idle,
      message: null,
      errorCode: null,
    );
    setLoading();
    try {
      LoginUsecase loginUsecase = ref.read(loginUsecaseProvider);
      RequestLogin request = RequestLogin(
        grantType: LoginGrantType.social.name,
        socialCode: state.socialCode,
        socialState: state.socialState,
        source: LoginSource.wechat_open.name,
        userName: state.account,
      );
      final ret = await loginUsecase.execute(request);
      Log.i("微信登录成功，token = ${ret.access_token}");
      final authStorage = ref.read(authStorageProvider.notifier);
      await authStorage.saveToken(ret.access_token);

      await ref.read(tuyaLoginProvider.notifier).login();
      final tuyaSuccess = ref.read(tuyaLoginStateProvider);
      if (!tuyaSuccess) {
        setFailure(msg: "登录失败，请稍后再试！");
        return;
      }
      setSuccess("登录成功");
    } on BusinessException catch (e) {
      setFailure(errorCode: e.code, msg: e.msg);
    } catch (e) {
      setFailure(msg: "登录失败，请稍后再试！");
    }
  }

  void verifyCode() async {
    if (step == WeChatLoginStep.sendCode) {
      step = WeChatLoginStep.verifyCode;
    } else {
      Log.e(
        "微信登录步骤错误,当前非WeChatLoginStep.sendCode步骤",
        Object(),
        StackTrace.current,
      );
      return;
    }
    state = state.copyWith(
      status: CommonNetStatus.loading,
      message: null,
      errorCode: null,
    );
    try {
      VerifyOtpUsecase verifyUsecase = ref.read(verifyOtpUsecaseProvider);
      final ret = await verifyUsecase.execute(
        state.account!,
        state.code!,
        ValideCodeType.login,
      );

      if (ret == true) {
        setSuccess("验证码正确");
      } else {
        setFailure(msg: "验证码错误");
      }
    } on BusinessException catch (e) {
      setFailure(errorCode: e.code, msg: e.msg);
    } catch (e) {
      setFailure(msg: "验证码校验失败");
      Log.e("验证码校验失败", e.toString(), StackTrace.current);
    }
  }

  // 绑定微信时，发送验证码
  void sendCode({SendCodeSource source = SendCodeSource.accountPage}) {
    step = WeChatLoginStep.sendCode;

    if (state.status == CommonNetStatus.loading) {
      return;
    }

    if (state.account == null) {
      return;
    }
    state = state.copyWith(
      source: source,
      status: CommonNetStatus.loading,
      message: null,
      errorCode: null,
      code: null,
    );
    if (state.account!.isEmail() == true) {
      _sendEmailCode();
      return;
    }

    if (state.account!.isPhoneNum() == true) {
      _sendSMSCode();
      return;
    }

    setFailure(msg: "账号格式错误");
  }

  // 设置账户，因为不需要触发重建或者响应，所以版本号不变
  void setAccount(String account) {
    state = state.copyWith(
      status: CommonNetStatus.idle,
      message: null,
      account: account,
      errorCode: null,
    );
  }

  void setCode(String code) {
    state = state.copyWith(
      status: CommonNetStatus.idle,
      message: null,
      code: code,
      errorCode: null,
    );
  }

  void _sendEmailCode() async {
    if (state.account == null) {
      return;
    }

    try {
      final emailUsecase = ref.read(sendEmailcodeProvider);

      final ret = await emailUsecase.execute(
        state.account!,
        ValideCodeType.login,
      );
      ret ? setSuccess("发送验证码成功") : setFailure(msg: "发送验证码失败，请稍后再试！");
    } on BusinessException catch (e) {
      setFailure(errorCode: e.code, msg: e.msg);
    } catch (e) {
      setFailure(msg: "发送验证码失败，请稍后再试！");
    }
  }

  void _sendSMSCode() async {
    if (state.account == null) {
      return;
    }

    try {
      final smsUsecase = ref.read(sendSmsUsecaseProvider);

      final ret = await smsUsecase.execute(
        state.account!,
        ValideCodeType.login,
      );
      ret.success ? setSuccess("发送验证码成功") : setFailure(msg: "发送验证码失败，请稍后再试！");
    } on BusinessException catch (e) {
      setFailure(errorCode: e.code, msg: e.msg);
    } catch (e) {
      setFailure(msg: "发送验证码失败，请稍后再试！");
    }
  }

  void resetStateAndStep() {
    step = WeChatLoginStep.auth;
    state = state.copyWith(
      status: CommonNetStatus.idle,
      message: null,
      errorCode: null,
      socialCode: null,
      socialState: null,
      account: null,
      code: null,
    );
  }

  @override
  LoginWechatState build() {
    ref.onDispose(() {
      Fluwx().removeSubscriber(_responseWechat1);
      Log.d("已经销毁：LoginWechatNotifier");
    });
    return LoginWechatState.initial();
  }
}
